package com.atzxh.java;

import static java.lang.Thread.sleep;

/**
 * 1.同步方法中仍然用到同步监视器
 *   静态方法中的监视器是: 当前类本身
 *   非静态方法的监视器是: this
 *
 * @author 小红同学
 * @creat 2021-11-09-18:13
 * @description       解决线程安全问题方式二: 同步方法
 */
class Window5 implements Runnable{

    private int ticket = 100;

    @Override
    public void run() {
        while(true){
           show();
        }
    }

    private synchronized void show(){     //此时同步监视器:this
        //synchronized (this){
            if(ticket > 0){
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"卖票,票号为:"+ticket);
                ticket--;
            }
        // }
    }
}

public class WindowTest4 {
    public static void main(String[] args) {
        Window5 w = new Window5();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();

    }
}
